package cn.rwklyd.BookKeeping.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class AsyncEmailService {

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 异步发送邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @return CompletableFuture<Boolean> 异步结果
     */
    @Async
    public CompletableFuture<Boolean> sendEmailAsync(String to, String subject, String content) {
        log.info("异步发送邮件到: {}", to);
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            
            helper.setFrom(fromEmail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true); // true表示支持HTML内容
            
            log.debug("准备发送邮件");
            mailSender.send(message);
            log.info("异步邮件发送成功");
            return CompletableFuture.completedFuture(true);
        } catch (MessagingException e) {
            log.error("异步邮件发送失败: {}", e.getMessage(), e);
            return CompletableFuture.completedFuture(false);
        }
    }
} 